package com.yneusoft.manage.handler;

import com.yneusoft.common.model.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class ArgumentNotValidExceptionHandler {


    /**
     * get请求参数校验
     * @param e ConstraintViolationException
     * @return ResponseWrapper
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseWrapper ConstraintViolationExceptionHandler(ConstraintViolationException e){
        log.info("<------ 参数校验异常 ");
        StringBuffer message = new StringBuffer();
        e.getConstraintViolations().forEach(error -> {
            message.append(error.getMessage()).append(",");
        });
        String result = message.toString();
        String errorInfo = result.substring(0, result.length() - 1);
        log.error(errorInfo+"------> ");
        return ResponseWrapper.markCustomError(errorInfo);
    }

    /**
     * form-data格式的参数校验
     * @param e BindException
     * @return ResponseWrapper
     */
    @ExceptionHandler(BindException.class)
    public ResponseWrapper bindExceptionHandler(BindException e){
        log.info("<------ 参数校验异常 ");
        StringBuffer message = new StringBuffer();
        e.getAllErrors().forEach(error -> {
            message.append(error.getDefaultMessage()).append(",");
        });
        String result = message.toString();
        String errorInfo = result.substring(0, result.length() - 1);
        log.error(errorInfo+"------> ");
        return ResponseWrapper.markCustomError(errorInfo);
    }


    /**
     * json格式的参数校验（Post）
     * @param e MethodArgumentNotValidException
     * @return ResponseWrapper
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseWrapper  handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.info("<------ 参数校验异常 ");
        String errorInfo = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(errorInfo+"------> ");
        return ResponseWrapper.markCustomError(errorInfo);
    }
}

